#!/bin/bash

while read line; do
  ip=`echo $line | cut -d " " -f1`        # 提取文件中的ip
  user=`echo $line | cut -d " " -f2`      # 提取文件中的用户名
  passwd=`echo $line | cut -d " " -f3`    # 提取文件中的密码
  home=`echo $line | cut -d " " -f4`      # 提取文件中的家目录

# 每台服务器生成 rsa 加密文件，并把 rsa 文件汇总到 1 台机器上
/usr/bin/expect <<-EOF
    spawn ssh ${user}@${ip} rm -rf ${home}/.ssh/*
    expect {
        "*y/n*" {send "y\r";exp_continue }
        "*yes/no*" {send "yes\r";exp_continue }
        "*password*" {send "${passwd}\r";exp_continue}
        "Overwrite*" {send "y\r";exp_continue}
        "Enter file in which to save the key*" { send "\r"; exp_continue}
        "Enter passphrase*" {send "\r";exp_continue }
        "Enter same passphrase again*" {send "\r"; exp_continue }
    }

    spawn ssh ${user}@${ip} ssh-keygen -t rsa
    expect {
        "*y/n*" { send "y\r";exp_continue }
        "*yes/no*" { send "yes\r";exp_continue }
        "*password*" { send "${passwd}\r";exp_continue}
        "Overwrite*" { send "y\r";exp_continue}
        "Enter file in which to save the key*" { send "\r"; exp_continue}
        "Enter passphrase*" { send "\r";exp_continue }
        "Enter same passphrase again*" { send "\r"; exp_continue }
    }

    spawn scp ${user}@${ip}:${home}/.ssh/id_rsa.pub /tmp/only-${ip}.pub
    expect {
        "*yes/no*" {send "yes\r";exp_continue}
        "*password*" {send "${passwd}\r";exp_continue}
    }
EOF
done < /root/host_list


# 将所有机器的 id_rsa.pub 放置到 authorized_keys 中
while read line; do
  ip=`echo $line | cut -d " " -f1`
  home=`echo $line | cut -d " " -f4`

  cat /tmp/only-${ip}.pub >> ${home}/.ssh/authorized_keys
  chmod 600 ~/.ssh/authorized_keys
done < /root/host_list


# 将 authorized_keys 放入到每台服务器主机的 ~/.ssh/ 目录下，同时生成多个集群的公钥指纹
while read line; do
  ip=`echo $line | cut -d " " -f1`
  user=`echo $line | cut -d " " -f2`
  passwd=`echo $line | cut -d " " -f3`
  home=`echo $line | cut -d " " -f4`
  host=`echo $line | cut -d " " -f5`

/usr/bin/expect <<EOF
  spawn scp ${home}/.ssh/authorized_keys ${user}@${ip}:${home}/.ssh/
  expect {
      "*yes/no*" {send "yes\r";exp_continue}
      "*password*" {send "${passwd}\r";exp_continue}
  }
EOF

ssh-keyscan -H ${ip} >> ${home}/.ssh/known_hosts
ssh-keyscan -H ${host} >> ${home}/.ssh/known_hosts

done < /root/host_list


# 将 known_hosts 放入到每台服务器主机的 ~/.ssh/ 目录下
while read line; do
  ip=`echo $line | cut -d " " -f1`
  user=`echo $line | cut -d " " -f2`
  home=`echo $line | cut -d " " -f4`

/usr/bin/expect <<EOF
  spawn scp ${home}/.ssh/known_hosts ${user}@${ip}:${home}/.ssh/
  expect {
      "*yes/no*" {send "yes\r";exp_continue}
  }
EOF
done < /root/host_list
